<script setup lang="ts">
  import { CirclePlusFilled } from '@element-plus/icons-vue'
  import TableCustom from '@/components/common/TableCustom.vue'
  import { ref } from 'vue'
  import { remove, saveOrUpdate, tree } from '@/api/category.ts'
  import { Category, CategorySaveOrUpdateParam } from '@/types'
  import { FormOption, TableColumns } from '@/types/form-option.ts'
  import TableEdit from '@/components/common/TableEdit.vue'
  import { ElMessage } from 'element-plus'
  import { normalizeColor } from '@/utils/color-util'

  const { columns, tableData, getData, handleDelete, handleAdd, handleEdit } = useTableCustom()
  const {
    cascaderProps,
    visible,
    isEdit,
    rowData,
    editColumns,
    closeDialog,
    updateData,
    colorPresets,
  } = useDialog()

  getData()

  //表格配置
  function useTableCustom() {
    // 表格配置
    const columns = ref<TableColumns[]>([
      { prop: 'name', label: '名字', align: 'left' },
      { prop: 'color', label: '颜色', width: 120, align: 'center' },
      { prop: 'count', label: '文章数', width: 100, align: 'center' },
      { prop: 'operator', label: '操作', width: 250, viewHidden: true },
    ])
    const tableData = ref()
    const getData = async () => {
      tableData.value = await tree({})
    }
    const handleDelete = async (row: Category) => {
      await remove({ id: row.id })
      ElMessage.success('删除成功')
      await getData()
    }
    const handleAdd = () => {
      rowData.value = {}
      visible.value = true
      isEdit.value = false
    }
    const handleEdit = (row: Category) => {
      visible.value = true
      isEdit.value = true
      rowData.value = row
    }

    return { columns, tableData, getData, handleDelete, handleAdd, handleEdit }
  }

  function useDialog() {
    //级联选择配置
    const cascaderProps = {
      checkStrictly: true, //严格的遵守父子节点不互相关联
      label: 'name',
      value: 'id',
      emitPath: false, //返回单个值
    }
    const visible = ref(false)
    const isEdit = ref(false)
    const rowData = ref()

    // 颜色预设值
    const colorPresets = [
      '#409EFF', // Element Plus 主蓝色
      '#67C23A', // 成功绿色
      '#E6A23C', // 警告橙色
      '#F56C6C', // 危险红色
      '#909399', // 信息灰色
      '#2D3748', // 深灰色
      '#805AD5', // 紫色
      '#38B2AC', // 青色
      '#DD6B20', // 橙色
      '#E53E3E', // 红色
      '#38A169', // 绿色
      '#3182CE', // 蓝色
      '#D69E2E', // 黄色
      '#9F7AEA', // 淡紫色
      '#4FD1C7', // 淡青色
      '#F687B3', // 粉色
    ]
    const editColumns: FormOption[] = [
      { type: 'input', prop: 'name', label: '名字' },
      { type: 'color', prop: 'color', label: '颜色' },
      { type: 'parent', label: '上级分类', prop: 'pid' },
    ]
    const closeDialog = () => {
      visible.value = false
      isEdit.value = false
    }
    const updateData = async (param: CategorySaveOrUpdateParam) => {
      // 转换颜色格式为标准的#FFFFFF格式
      if (param.color) {
        param.color = normalizeColor(param.color) || param.color
      }

      await saveOrUpdate(param)
      ElMessage.success('保存成功')
      closeDialog()
      await getData()
    }

    return {
      cascaderProps,
      visible,
      isEdit,
      rowData,
      editColumns,
      closeDialog,
      updateData,
      colorPresets,
    }
  }
</script>

<template>
  <div>
    <div class="container">
      <TableCustom
        :columns="columns"
        :table-data="tableData"
        row-key="id"
        :has-pagination="false"
        :del-func="handleDelete"
        :edit-func="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        </template>
        <template #color="{ row }">
          <div v-if="row.color" class="color-display">
            <span class="color-box" :style="{ backgroundColor: row.color }"></span>
            <span class="color-text">{{ row.color }}</span>
          </div>
          <span v-else class="text-gray-400">未设置</span>
        </template>
        <template #count="{ row }">
          <el-tag :type="row.count > 0 ? 'success' : 'info'" size="small">
            {{ row.count || 0 }}
          </el-tag>
        </template>
      </TableCustom>
    </div>

    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑' : '新增'"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        label-width="100px"
        :span="12"
        :columns="editColumns"
        :edit="isEdit"
        :update="updateData"
      >
        <template #parent="{ row }">
          <el-cascader v-model="row.pid" :options="tableData" :props="cascaderProps" clearable />
        </template>
        <template #color="{ row }">
          <el-color-picker
            v-model="row.color"
            :predefine="colorPresets"
            show-alpha
            @active-change="
              (color: string | null) => {
                if (color) row.color = color
              }
            "
          />
        </template>
      </TableEdit>
    </el-dialog>
  </div>
</template>

<style scoped>
  .color-display {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .color-box {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
  }

  .color-text {
    font-size: 12px;
    color: #606266;
  }
</style>
